//
//  CuzyManager.m
//  JDong
//
//  Created by liu nian on 13-12-10.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "CuzyManager.h"
#import "CuzyAdSDK.h"
#import "AuthorizeManager.h"

@interface CuzyManager ()<CuzyAdSDKDelegate>{
    BOOL    _isAuthorize;
}

@end
static CuzyManager * sharedManager;
@implementation CuzyManager

+ (CuzyManager *)sharedManager{
    if (!sharedManager) {
        sharedManager = [[CuzyManager alloc] init];
    }
    return sharedManager;
}

- (id)init
{
    self = [super init];
    if (self) {

        
    }
    return self;
}
- (void)authorize{
    [[AuthorizeManager sharedInstance] authorize];
}

#pragma mark CuzyAdSDKDelegate
-(void)registerAppSucceed{
    _isAuthorize = YES;
}

-(void)registerAppFailed{
    _isAuthorize = NO;
}

- (void)requstTBKItemsWithKeyWord:(NSString*)searchKey
                      WithThemeID:(NSString *)themeId
                  WithPicSizeType:(PicSizeType)PSType
                         WithSort:(NSString *)sort
                    WithPageIndex:(NSInteger)pageIndex
                     withDelegate:(id<CuzyManagerDelegate>)aDelegate{
    _delegate = aDelegate;
    if (![AuthorizeManager sharedInstance].isAuthorized) {
        [[AuthorizeManager sharedInstance] requestForAuthorizeSucc:^{
            [self requstTBKItemsWithKeyWord:searchKey
                                WithThemeID:themeId
                            WithPicSizeType:PSType
                                   WithSort:sort
                              WithPageIndex:pageIndex
                               withDelegate:aDelegate];
        }
                                                              Fail:^{
                                                                  [aDelegate updateViewForSuccess:nil];

                                                              }];
        return;
    }
    if (sort) {
        [[CuzyAdSDK sharedAdSDK] setItemSortingMethod:sort];
    }else{
        [[CuzyAdSDK sharedAdSDK] setItemSortingMethod:@"commission_rate_desc"];
    }
    
    if (PSType == PicSize600) {
        [[CuzyAdSDK sharedAdSDK] setRawItemPicSize:@"600x600"];
    }else if (PSType == PicSize400){
        [[CuzyAdSDK sharedAdSDK] setRawItemPicSize:@"400x400"];
    }else{
        [[CuzyAdSDK sharedAdSDK] setRawItemPicSize:@"360x360"];
    }

    dispatch_async(kBgQueue, ^{
        NSArray *array = nil;
        if (themeId || searchKey) {
            array = [[CuzyAdSDK sharedAdSDK] fetchRawItemArraysWithThemeID:themeId
                                                          orSearchKeywords:searchKey
                                                             withPageIndex:pageIndex];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            //update the UI in main queue;
            [aDelegate updateViewForSuccess:array];
        });
    });
}

@end
